



SAMPLING_FREQUENCY=100
# CURRENT_ADJUSTMENT_PERIOD_MS=500
# IR_LED_CURRENT=15                    //  MAX30100_LED_CURR_50MA
RED_LED_CURRENT_START =8
# DC_REMOVER_ALPHA=0.95

# #PulseOximeterState
# PULSEOXIMETER_STATE_INIT=0
# PULSEOXIMETER_STATE_IDLE=1
# PULSEOXIMETER_STATE_DETECTING=2
# #PulseOximeterDebuggingMode
# PULSEOXIMETER_DEBUGGINGMODE_NONE=0
# PULSEOXIMETER_DEBUGGINGMODE_RAW_VALUES=1
# PULSEOXIMETER_DEBUGGINGMODE_AC_VALUES=2
# PULSEOXIMETER_DEBUGGINGMODE_PULSEDETECT=3

# onBeatDetected=0.0

# PulseOximeterState state;
# PulseOximeterDebuggingMode debuggingMode;
# uint32_t tsFirstBeatDetected;
# uint32_t tsLastBeatDetected;
# uint32_t tsLastSample;
# uint32_t tsLastBiasCheck;
# uint32_t tsLastCurrentAdjustment;
# uint8_t redLedPower;

# ID=0
# TempINT=0
# TempFRAC=0
import wiringpi as gpio
import max30100
import beatDetecor
import SpO2cCalculator

class PulseOximeter(object):

    def __init__ (self):

        self.state=0
        self.tsFirstBeatDetected=0
        self.tsLastBeatDetected=0
        self.tsLastSample=0
        self.tsLastBiasCheck=0
        self.tsLastCurrentAdjustment=0
        self.redLedPower=RED_LED_CURRENT_START
        self.onBeatDetected=None
        self.irDCRemover={'alpha':0.0,'dcw':0.0}
        self.redDCRemover={'alpha':0.0,'dcw':0.0}
        self.filteredPulseValue=0.0
        self.beatDetected=0
        self.redACValue=0.0
        self.irACValue=0.0
        self.HeartRate=0
        self.SPO2=0
        self.max  = max30100.MAX30100()




    def begin(self,mode):
        self.debuggingMode = mode
        self.irDCRemover['alpha']=0.95
        self.irDCRemover['dcw']=0
        self.redDCRemover['alpha']=0.95
        self.redDCRemover['dcw']=0
        state = 1

    def spo2_init(self):
        self.max.refresh_temperature()

        self.max.set_mode(3)
        self.max.set_spo_config()
        self.max.set_led_current()
        self.beat = beatDetecor.BeatDetector()
        # self.onBeatDetected=self.onbeatDetected
        self.begin(3)



    def POupdate(self):
        # if(gpio.millis()-self.tsLastSample>1.0/SAMPLING_FREQUENCY*1000.0):
        #     self.tsLastSample = gpio.millis()
        self.max.read_sensor()
        self.redACValue= self.max.buffer_red.pop()+(self.redDCRemover['alpha'])*(self.redDCRemover['dcw'])
        self.irACValue= self.max.buffer_ir.pop()+(self.irDCRemover['alpha'])*(self.irDCRemover['dcw'])
        v=[0.0,0.0]
        v[1]=(2.452372752527856026e-1 * (-self.irACValue))+ (0.50952544949442879485 * v[0])
        self.filteredPulseValue =v[1]+v[0]

        # self.beatDetected = beatDetecor.BeatDetector().checkForBeat(self.filteredPulseValue)
        spo2 = SpO2cCalculator.SpO2Calculator()
        spo2.SPO2update(self.irACValue,self.redACValue)
        print("spo2:{}%".format(spo2.get_spo2()))
        print("HearRate:{}".format(self.beat.getRate()))
        spo2.reset()


